package com.ruoyi.monitormanage.service.impl;

import com.ruoyi.common.core.domain.Parameter;
import com.ruoyi.common.core.domain.Quaparameter;
import com.ruoyi.common.core.domain.dto.QualityMonitorDataDTO;
import com.ruoyi.common.core.feign.ModulesSystemFeign;
import com.ruoyi.common.core.utils.CryptoUtils;
import com.ruoyi.common.core.utils.Desensitization;
import com.ruoyi.common.core.utils.Global;
import com.ruoyi.monitormanage.domain.PersonResult;
import com.ruoyi.monitormanage.domain.TestWholeDataExt;
import com.ruoyi.monitormanage.mapper.QualityMapper;
import com.ruoyi.monitormanage.service.QualityService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QualityServiceImpl implements QualityService {
    @Autowired
    private QualityMapper qualityMapper;
    @Autowired
    public ModulesSystemFeign systemFeign;
    @Override
    public Map<String,Object> getqualitycontrol(Quaparameter quaparameter) {
        Map<String, Object> map = new HashMap<String, Object>();
        Parameter parameter = systemFeign.setParameter(quaparameter);
        BeanUtils.copyProperties(parameter, quaparameter);
        if ((quaparameter.getIdcard() != null && !quaparameter.getIdcard().isEmpty())) {
            quaparameter.setStart(0);
            try {
                quaparameter.setIdcard(CryptoUtils.encryptSymmetrically(Global.COLS_AES_SECRETKEY, null, quaparameter.getIdcard(), CryptoUtils.Algorithm.Encryption.AES_ECB_PKCS5)
                );
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if ((quaparameter.getName() != null && !quaparameter.getName().isEmpty())) {
            quaparameter.setStart(0);
            try {
                quaparameter.setName(CryptoUtils.encryptSymmetrically(Global.COLS_AES_SECRETKEY, null, quaparameter.getName(), CryptoUtils.Algorithm.Encryption.AES_ECB_PKCS5)
                );
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        quaparameter.setStart((quaparameter.getPage()-1)*quaparameter.getLimit());
        List<TestWholeDataExt> data = qualityMapper.getqualitycontrol(quaparameter);
        long count = qualityMapper.getCount(quaparameter);
        // 查询总条数
        //对data中的realname,idcard,address,workunit,phone隐藏中间位
        for (TestWholeDataExt testWholeData : data) {
            testWholeData.setIdcard(Desensitization.idCardDesensitization(testWholeData.getIdcard()));
            testWholeData.setRealname(Desensitization.desensitizedName(testWholeData.getRealname()));
            testWholeData.setAddress(Desensitization.desValue(testWholeData.getAddress(),3,3,"****"));
            testWholeData.setWorkunit(Desensitization.desValue(testWholeData.getWorkunit(),3,3,"****"));
            testWholeData.setPhone(Desensitization.mobilePhoneDesensitization(testWholeData.getPhone()));
        }
        map.put("data",data);
        map.put("count",count);
        return map;
    }

    @Override
    public PersonResult getqualityresult(TestWholeDataExt testWholeDataExt) {
        return qualityMapper.getqualityresult(testWholeDataExt);
    }

    @Override
    public List<QualityMonitorDataDTO> qualityMonitorData(Quaparameter quaparameter) {
        // 保存子类字段的临时值
        String tempIdcard = quaparameter.getIdcard();
        String tempName = quaparameter.getName();
        int tempStart = quaparameter.getStart();
        int tempLimit = quaparameter.getLimit();
        int tempPage = quaparameter.getPage();
        String tempIspassscreening = quaparameter.getIspassscreening();
        String tempSex = quaparameter.getSex();
        String tempTowncountry = quaparameter.getTowncountry();
        Integer tempPeopleTypeId = quaparameter.getPeopleTypeId();
        Integer tempAgeGroupId = quaparameter.getAgeGroupId();

        Parameter parameter = systemFeign.setParameter(quaparameter);
        BeanUtils.copyProperties(parameter, quaparameter);
        // 恢复子类字段
        quaparameter.setIdcard(tempIdcard);
        quaparameter.setName(tempName);
        quaparameter.setStart(tempStart);
        quaparameter.setLimit(tempLimit);
        quaparameter.setPage(tempPage);
        quaparameter.setIspassscreening(tempIspassscreening);
        quaparameter.setSex(tempSex);
        quaparameter.setTowncountry(tempTowncountry);
        quaparameter.setPeopleTypeId(tempPeopleTypeId);
        quaparameter.setAgeGroupId(tempAgeGroupId);


        QualityMonitorDataDTO totalMap = new QualityMonitorDataDTO();//合计结果
        double wancheng = 0.00, samplenum = 0.00, ispass = 0.00, isnotpass = 0.00;
        double ispasspercentage = 0.0, finishper = 0.0;
        Map<String,Integer> map = systemFeign.getTestPointNum(parameter);
        Integer testPointNum = map.get("testPointNum");
        Integer cityTestPointNum = map.get("cityTestPointNum");
        //机构代码是省级	总数-2的个数	或者3
        //机构代码是市级=4	上级同一城市分类是否有2，1/2
        //机构代码是区级	上级市是否属于抽样市，属于同市级，不属于为0
        //机构代码是监测点	同市级
        //根据机构代码查询抽样点个数，计算各年龄组各城乡各性别需要测试的目标人数
        	/*if (14 == organizationCode.length()) {
        		//根据用户选择区域的机构代码，年份，抽样点类型查询抽样点个数
        		testPointNum = 1;
        	}else {
        		//根据用户选择区域的机构代码，年份，抽样点类型是1（指国测点）的条件查询抽样点个数
        		testPointNum = orgMapper.getTestPointNum(organizationCode,year,"1");
        	}*/
        //国民体质测试完整数据表名guomintizhiceshiTableName
        List<QualityMonitorDataDTO> data = qualityMapper.getQualityMonitorData(quaparameter);
        /*List<QualityMonitorDataDTO> filteredData = data.stream()
                .filter(datum -> !(datum.getWancheng() == 0 &&
                        datum.getIspasspercentage() == 0 &&
                        datum.getIspass() == 0 &&
                        datum.getIsnotpass() == 0))
                .collect(Collectors.toList());*/
        for (QualityMonitorDataDTO datum : data) {
            if (quaparameter.getOrganizationCode().length() >= 4) {
                datum.setSamplenum(0 == cityTestPointNum ? 0 : datum.getSamplenum() / cityTestPointNum * testPointNum);
            } else {
                datum.setSamplenum(datum.getSamplenum() * testPointNum);
            }

            double num = 0.0;
            if (0 != datum.getSamplenum()) {
                num = datum.getWancheng() * 100 / datum.getSamplenum();
            }
            datum.setFinishper(roundToTwoDecimalPlaces(num));
            wancheng += datum.getWancheng();
            samplenum += datum.getSamplenum();
            ispass += datum.getIspass();
            isnotpass += datum.getIsnotpass();
        }

        if(0 != wancheng) {
            ispasspercentage = roundToTwoDecimalPlaces(ispass*100/wancheng);
        }
        if(0 != samplenum) {
            finishper = roundToTwoDecimalPlaces(wancheng*100/samplenum);
        }
        totalMap.setPeopletypename("合计");
        totalMap.setTowncountry("合计");
        totalMap.setAgegroupname("合计");
        totalMap.setSex("合计");
        totalMap.setWancheng(wancheng);
        totalMap.setSamplenum(samplenum);
        totalMap.setIspass(ispass);
        totalMap.setIsnotpass(isnotpass);
        totalMap.setIspasspercentage(ispasspercentage);
        totalMap.setFinishper(finishper);
//        if(totalMap.getWancheng()!=0 && totalMap.getIspasspercentage()!=0 && totalMap.getIspass()!=0 && totalMap.getIsnotpass()!=0){
            data.add(totalMap);
//        }
        return data;
    }

    private double roundToTwoDecimalPlaces(double value) {
        return new BigDecimal(value).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }
}
